package deng.java.examples.xml;

import java.io.InputStream;
import java.net.URL;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.junit.Test;
import org.w3c.dom.Document;

public class SchemaValidationJEEApp5 {
	@Test
	public void validateJavaEEApplicationXml() throws Exception {
		SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
		Schema schema = sf.newSchema(new URL("http://java.sun.com/xml/ns/javaee/application_5.xsd"));
		Validator validator = schema.newValidator();
		Source source = createClasspathSource("META-INF/application.xml");
		validator.validate(source);
	}

	private Source createClasspathSource(String resName) throws Exception {
		InputStream is = getClass().getClassLoader().getResource(resName).openStream();
		DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = parser.parse(is);
        return new DOMSource(document);
	}
}
